using System.Text;
using System.Text.Json;
using RabbitMQ.Client;
using MasterNeverDown.Model;

namespace MasterNeverDown.Modbus
{
    public class ModbusPublisher : IAsyncDisposable
    {
        private readonly ILogger<ModbusPublisher> _logger;
        private IConnection _connection;
        private IChannel _channel;
        private readonly IConfiguration _configuration;
        private readonly string _exchangeName;
       
        
        public ModbusPublisher(ILogger<ModbusPublisher> logger, IConfiguration configuration)
        {
            _logger = logger;
            _configuration = configuration;
            
            _logger.LogInformation("ModbusHostService is starting.");

            
        }

        public async Task PublishAsync(ModbusSubscription subscription, CancellationToken cancellationToken = default)
        {
            var factory = new ConnectionFactory { HostName = _configuration["RabbitMQ:HostName"] ?? throw new InvalidOperationException("RabbitMQ:HostName is null") };

            _connection = await factory.CreateConnectionAsync(cancellationToken);
            _channel = await _connection.CreateChannelAsync(cancellationToken: cancellationToken);
         
           
                    // 声明队列
                 await   _channel.QueueDeclareAsync(queue: "demoQueue",
                        durable: false,
                        exclusive: false,
                        autoDelete: false,
                        arguments: null, cancellationToken: cancellationToken);

                    // 要发布的消息
                    string message = "Hello, RabbitMQ!";
                    var body = Encoding.UTF8.GetBytes(message);

                    // 发布消息
                   await _channel.BasicPublishAsync(exchange: _exchangeName, routingKey: "", basicProperties: null, body: body
    cancellationToken: cancellationToken);
                    Console.WriteLine($" [x] Sent {message}");
               

            Console.WriteLine(" Press [enter] to exit.");
            Console.ReadLine();
        }

        public async ValueTask DisposeAsync()
        {
            await _channel.CloseAsync();
            await _connection.CloseAsync();
        }
    }
}